//
//  UIView+Extension.swift
//  Swift0319
//
//  Created by admin on 2017/3/20.
//  Copyright © 2017年 __MyCompanyName__. All rights reserved.
//

import UIKit
import SDWebImage

extension UIImage{
    // 获取主屏幕的内容图片
    class func getScreenSnap() -> UIImage?{
        // 获取主window
        let window = UIApplication.shared.keyWindow!
        // 开启上下文
        UIGraphicsBeginImageContext(window.bounds.size)
        // 将主window渲染到上下文中
        window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
        // 通过上下文获取对应的image
        let image = UIGraphicsGetImageFromCurrentImageContext()
        // 关闭上下文
        UIGraphicsEndImageContext()
        return image
    }
    
    //对图片进行压缩处理
    func dealImageScale(maxWidth: CGFloat)-> UIImage{
        if self.size.width < maxWidth{
            return self
        }
        let maxH = self.size.height * maxWidth / self.size.width
        let rect = CGRect(x: 0, y: 0, width: maxWidth, height: maxH)
        UIGraphicsBeginImageContext(rect.size)
        self.draw(in: rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
}


// 快速创建UIImageView
extension UIImageView{
    
    convenience init(imgName: String){
        self.init(image: UIImage(named: imgName))
    }
    

    func lc_setImage(urlString: String?, placeholderImgName: String?){

        
        self.sd_setImage(with: URL(string: urlString ?? ""), placeholderImage: UIImage.init(named: placeholderImgName ?? ""))
        
    }
    
}

extension UILabel{
    convenience init(title: String, textColor: UIColor, fontSize: CGFloat) {
        self.init();
        self.text = title;
        self.textColor = textColor;
        self.font = UIFont.systemFont(ofSize: fontSize);
        
        //换行
        self.numberOfLines = 0;
//        self.textAlignment = .center;
        
        self.sizeToFit();
    }
}
extension UIButton{
    convenience init(title: String, textColor: UIColor, fontSize: CGFloat, backImageName: String , imageName: String? = nil) {
        self.init()
        self.setTitle(title, for: .normal);
        self.setTitleColor(textColor, for: .normal);
        self.titleLabel?.font = UIFont.systemFont(ofSize: fontSize);
        self.setBackgroundImage(UIImage.init(named: backImageName), for: .normal);
        if let img = imageName {
            self.setImage(UIImage.init(named: img), for: .normal);
        }
    }

}
